<template>
  <!-- 相关方评定 -->
  <div class="relatedpartyjudge">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        v-model="form"
        ref="crud"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 状态列表格自定义 -->
        <template slot="status" slot-scope="scope">
          <el-tag size="small" type="success" v-if="scope.row['zf'] !== 0 && scope.row['zf'] !== ''">已评分</el-tag>
          <el-tag size="small" type="danger" v-else>待评分</el-tag>
        </template>

        <!-- 操作列表格自定义 -->
        <template slot="operation" slot-scope="scope">
          <el-button
            :disabled="scope.row['zf'] !== 0 && scope.row['zf'] !== ''"
            type="success"
            size="mini"
            icon="el-icon-edit-outline"
            @click="handleJudge(scope.row)">
            评 定
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click="handleQuery(scope.row)">
            查 看
          </el-button>
        </template>

      </avue-crud>

      <!-- 弹窗：评定相关方 -->
      <el-dialog 
        title="评定相关方"
        append-to-body
        :visible.sync="judgeRelatedPartyDialog"
        :close-on-click-modal="false" 
        :before-close="closeJudgeRelatedPartyDialog"
        width="60%"
        class="judge_related_party_dialog"
      >

        <!-- 内容 -->
        <avue-form 
          ref="judgeForm" 
          v-model="judgeObj" 
          :option="judgeOption" 
        >
          <!-- 评审附件表单自定义 -->
          <template slot="zf" slot-scope="scope">
            <div>
              <el-button 
                :disabled="dialogType === 'view'"
                type="success"
                size="small"
                icon="el-icon-edit-outline"
                @click="calculateJudgeScore()">
                分数计算
              </el-button>
              <span style="margin-left:15px;font-weight:bold;font-size:18px;">{{scope.value}}</span>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              type="primary"
              icon="el-icon-check"
              @click="confirmJudgeRelatedParty()">
              确 定
            </el-button>
            <el-button 
              v-if="dialogType !== 'view'"
              size="small"
              icon="el-icon-close"
              @click="closeJudgeRelatedPartyDialog()">
              取 消
            </el-button>
          </template>

        </avue-form>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  update,
  getJudgeItems
} from "@/api/basedata/interestedpartymange/relatedpartyjudge";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: false,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menu: false,
        column: [
          {
            label: "单位名称",
            prop: "dwmc",
            align: "center",
            search: true
          },
          {
            label: "评定人",
            prop: "pdryName",
            align: "center"
          },
          {
            label: "评分",
            prop: "zf",
            width: 100,
            align: "center",
          },
          {
            label: "评定等级",
            prop: "pddj",
            align: "center",
            search: true,
            type: "select",
            dicData: [{
              label: '优',
              value: '优'
            }, {
              label: '良',
              value: '良'
            }, {
              label: '中',
              value: '中'
            }, {
              label: '差',
              value: '差'
            }]
          },
          {
            label: "状态",
            prop: "status",
            align: "center",
            slot: true
          },
          {
            label: "操作",
            prop: "operation",
            align: "center",
            slot: true,
            width: 200
          }
        ]
      },
      // 弹窗：评定
      judgeItems: [],
      judgeRelatedPartyDialog: false,
      judgeObj: {},
      dialogType: ""
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: false,//this.vaildData(this.permission.relatedpartyjudge_add, false),
        viewBtn: false,//this.vaildData(this.permission.relatedpartyjudge_view, false),
        delBtn: false,//this.vaildData(this.permission.relatedpartyjudge_delete, false),
        editBtn: false,//this.vaildData(this.permission.relatedpartyjudge_edit, false)
      };
    },

    judgeOption() {
      return {
        size: "small",
        labelWidth: 110,
        submitBtn: false,
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "单位名称",
            prop: "dwmc",
            disabled: true,
            span: 24,
            rules: [{
              required: true,
              message: "请对输入单位名称",
              trigger: "blur"
            }]
          }
        ]
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化数据
    initData() {
      getJudgeItems().then(res => {
        this.judgeItems = res.data.data;
        this.judgeItems.forEach(item => {
          this.judgeOption.column.push({
            label: item.pdnr,
            prop: "ITEM_" + item.id,
            type: "radio",
            span: 12,
            disabled: true,
            dicData: [{
              label: '优',
              value: 95
            }, {
              label: '良',
              value: 85
            }, {
              label: '中',
              value: 75
            }, {
              label: '差',
              value: 60
            }],
            rules: [{
              required: true,
              message: "请对" + item.pdnr + "进行评分",
              trigger: "change"
            }]
          });
        });
        this.judgeOption.column.push({
          label: "分数计算",
          prop: "zf",
          span: 24,
          slot: true,
          formslot: true,
          rules: [{
            required: true,
            message: "请计算评定平均分",
            trigger: "blur"
          }]
        });
        this.judgeOption.column.push({
          label: "评定等级",
          prop: "pddj",
          span: 24,
          disabled: true,
          type: "select",
          dicData: [{
            label: '优',
            value: '优'
          }, {
            label: '良',
            value: '良'
          }, {
            label: '中',
            value: '中'
          }, {
            label: '差',
            value: '差'
          }],
          rules: [{
            required: true,
            message: "请选择评定等级",
            trigger: "change"
          }]
        });
      }).then(() => {
        this.onLoad(this.page);
      });
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },

    /**
     * 弹窗：评定
    */

    // 打开评定弹窗
    handleJudge(row) {
      this.dialogType = "edit";
      this.judgeObj = this.formatJudgeObj(row);
      this.judgeOption.column.forEach(item => {
        if(item.prop.indexOf("ITEM_") === 0) {
          item.disabled = false;
        }
      });
      this.judgeRelatedPartyDialog = true;
    },

    // 格式化评定数据
    formatJudgeObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      this.judgeItems.forEach(item => {
        data["ITEM_" + item.id] = "";
      });
      return data;
    },

    // 分数计算
    calculateJudgeScore() {
      var isEmpty = false;
      var calculateItems = [];
      for(var key in this.judgeObj) {
        if(key.indexOf("ITEM_") === 0) {
          if(this.judgeObj[key] === "" || this.judgeObj[key] === undefined || this.judgeObj[key] === 0) {
            isEmpty = true;
          } else {
            calculateItems.push(this.judgeObj[key]);
          }
        }
      }
      if(isEmpty) {
        this.$message.warning("未评定全部内容!");
        return;
      }
      var summaryScore = 0;
      for(let i = 0 ; i < calculateItems.length ; i++) {
        summaryScore = summaryScore + calculateItems[i];
      } 
      this.judgeObj.zf = (summaryScore / calculateItems.length).toFixed(2);
      if(this.judgeObj.zf >= 90) {
        this.judgeObj.pddj = "优";
      } else if(this.judgeObj.zf >= 80 && this.judgeObj.zf < 90) {
        this.judgeObj.pddj = "良";
      } else if(this.judgeObj.zf >= 70 && this.judgeObj.zf < 80) {
        this.judgeObj.pddj = "中";
      } else {
        this.judgeObj.pddj = "差";
      }
    },

    // 关闭、取消评定弹窗
    closeJudgeRelatedPartyDialog() {
      this.judgeRelatedPartyDialog = false;
      this.judgeObj = {};
    },

    // 确认评定计划
    confirmJudgeRelatedParty() {
      if(this.dialogType === "view") {
        this.closeJudgeRelatedPartyDialog();
        return;
      }
      this.$refs.judgeForm.validate((vaild,done)=>{
        if(vaild){
          var row = {
            id: this.judgeObj.id,
            pddj: this.judgeObj.pddj,
            relatedPartyJudgePlanId: this.judgeObj.relatedPartyJudgePlanId,
            zf: this.judgeObj.zf,
            scoreList: []
          };
          for(var key in this.judgeObj) {
            if(key.indexOf("ITEM_") === 0) {
              row.scoreList.push({
                pdfs: this.judgeObj[key],
                relatedJudgeItemId: key.substring(5)
              });
            }
          }
          update(row).then(res => {
            if(res.data.success) {
              this.closeJudgeRelatedPartyDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
          done();
        }
      })
    },

    // 查看评定详情
    handleQuery(row) {
      this.dialogType = "view";
      this.judgeOption.column.forEach(item => {
        if(item.prop.indexOf("ITEM_") === 0) {
          item.disabled = true;
        }
      });
      getDetail(row.id).then(res => {
        this.judgeObj = this.formatQueryObj(res.data.data);
      }).then(() => {
        this.judgeRelatedPartyDialog = true;
      });
    },

    // 格式化查看时的评定详情
    formatQueryObj(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      row.scoreList.forEach(item => {
        data["ITEM_" + item.relatedJudgeItemId] = item.pdfs;
      });
      return data;
    },

  }
};
</script>

<style lang="scss">
.judge_related_party_dialog {
  .avue-form__menu--center {
    text-align: center !important;
    margin-bottom: 0px;
  }
}
</style>